package com.sys.controller;

import com.sys.bean.History;
import com.sys.bean.RespBean;
import com.sys.service.CarService;
import com.sys.service.HistoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@CrossOrigin
@RestController
@RequestMapping("/admin/historyController")
public class HistoryCntroller {
    @Autowired
    private HistoryService historyService;
    @Autowired
    private CarService carService;
    //查询所有记录
    @RequestMapping("/selectAll")
    @GetMapping
    public RespBean selectAll(){
        List<History> historyList = historyService.selectAll();
        return RespBean.ok("查询成功",historyList);
    }
    //获取所停车辆信息和已停泊车辆的信息
    @GetMapping("/allHistory/{parkId}")
    public RespBean AllCars(@PathVariable("parkId") Integer parkId) {
        List<Map<String, Object>> carMapList = carService.selectByOwnerName(null)
                //存储到流中
                .stream()
                // 过滤出状态为在库的车辆
                .filter(car -> car.getCarState() == 1)
                //将 在库车辆 car 转换为 Map
                .map(car -> {
                    Map<String, Object> carMap = new HashMap<>();
                    carMap.put("key", car.getCarId());
                    carMap.put("label", car.getCarPlate() + "-" + "-" + car.getOwnerName());
                    return carMap;
                }).collect(Collectors.toList());
        //获取已停泊车辆的信息
        List<Integer> carIds = historyService.selectCarIdByParkId(parkId);
        Map<String, Object> map = new HashMap<>();
        map.put("allCar",carMapList);
        map.put("selectedCarId",carIds);
        return RespBean.ok("查询成功",map);
    }

    @PostMapping("/parkIdAndCarId")
    public RespBean insertParkIdAndCarId(@RequestBody Map<String, Object> map){
        System.out.println(map);
        Integer parkId = (Integer) map.get("parkId");
        List<Integer> carIdsList = (List<Integer>) map.get("carIds");
        Integer[] carIds = new Integer[carIdsList.size()];
        for (int i = 0; i < carIdsList.size(); i++){
            int carId = carIdsList.get(i);
            carIds[i] = new Integer(carId + "");
        }
        historyService.insert(parkId, carIds);
        return RespBean.ok("车辆分配成功");
    }
}
